{% extends "base.html" %}

{% block content %}
<!-- 内容管理页面 -->
<div class="content-section">
    <div class="section-header">
        <h2 class="section-title">内容管理</h2>
        <div style="display: flex; gap: 10px;">
            <button class="btn btn-primary" onclick="refreshContents()">刷新</button>
        </div>
    </div>
    <div class="section-content">
        <!-- 筛选器 -->
        <div style="margin-bottom: 20px; display: flex; gap: 15px; align-items: center;">
            <label>平台：</label>
            <select id="platformFilter" onchange="filterContents()">
                <option value="">全部</option>
                <option value="weibo">微博</option>
                <option value="twitter">Twitter</option>
                <option value="wechat">微信公众号</option>
            </select>
            
            <label>状态：</label>
            <select id="statusFilter" onchange="filterContents()">
                <option value="">全部</option>
                <option value="pending">待发布</option>
                <option value="published">已发布</option>
                <option value="failed">发布失败</option>
            </select>
        </div>

        <!-- 内容列表 -->
        <div id="contentsList">
            {% if contents %}
            <ul class="item-list">
                {% for content in contents %}
                <li class="item">
                    <div style="flex: 1;">
                        <div class="item-title">
                            {{ content.content[:100] }}{% if content.content|length > 100 %}...{% endif %}
                        </div>
                        <div class="item-meta">
                            平台: {{ content.platform }} | 
                            状态: {{ content.status }} | 
                            创建时间: {{ content.created_at.strftime('%Y-%m-%d %H:%M') }}
                            {% if content.published_at %}
                            | 发布时间: {{ content.published_at.strftime('%Y-%m-%d %H:%M') }}
                            {% endif %}
                        </div>
                        {% if content.hashtags %}
                        <div style="margin-top: 5px; color: #666; font-size: 0.9rem;">
                            标签: {{ content.hashtags }}
                        </div>
                        {% endif %}
                    </div>
                    <div style="display: flex; flex-direction: column; gap: 5px; align-items: flex-end;">
                        {% if content.status == 'pending' %}
                        <span class="badge badge-warning">待发布</span>
                        <button class="btn btn-primary" style="font-size: 0.8rem; padding: 0.25rem 0.5rem;" 
                                onclick="publishContent({{ content.id }})">
                            发布
                        </button>
                        {% elif content.status == 'published' %}
                        <span class="badge badge-success">已发布</span>
                        {% elif content.status == 'failed' %}
                        <span class="badge badge-error" style="background-color: #f8d7da; color: #721c24;">发布失败</span>
                        <button class="btn btn-primary" style="font-size: 0.8rem; padding: 0.25rem 0.5rem;" 
                                onclick="publishContent({{ content.id }})">
                            重试发布
                        </button>
                        {% endif %}
                        <span class="badge badge-info">{{ content.platform }}</span>
                    </div>
                </li>
                {% endfor %}
            </ul>
            
            <!-- 批量操作 -->
            <div style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 5px;">
                <h4>批量操作</h4>
                <div style="display: flex; gap: 10px; margin-top: 10px;">
                    <button class="btn btn-primary" onclick="publishPendingContents()">
                        发布所有待发布内容
                    </button>
                    <button class="btn btn-primary" onclick="publishSelectedPlatform()">
                        发布选中平台内容
                    </button>
                </div>
            </div>
            {% else %}
            <div class="empty-state">
                <p>暂无生成内容</p>
                <a href="/admin/trends" class="btn btn-primary">去生成内容</a>
            </div>
            {% endif %}
        </div>
    </div>
</div>

<!-- 内容详情弹窗 -->
<div id="contentModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;">
    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 2rem; border-radius: 10px; max-width: 600px; width: 90%;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;">
            <h3>内容详情</h3>
            <button onclick="hideContentModal()" style="background: none; border: none; font-size: 1.5rem; cursor: pointer;">&times;</button>
        </div>
        <div id="contentDetails"></div>
        <div style="margin-top: 1rem; text-align: right;">
            <button class="btn btn-primary" onclick="hideContentModal()">关闭</button>
        </div>
    </div>
</div>

<!-- 加载提示 -->
<div id="loadingModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;">
    <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; padding: 2rem; border-radius: 10px; text-align: center;">
        <div style="margin-bottom: 1rem;">⏳ 处理中...</div>
        <div id="loadingText">请稍候</div>
    </div>
</div>

<script>
async function publishContent(contentId) {
    showLoading('正在发布内容，请稍候...');
    
    try {
        const response = await fetch('/api/v1/publish/publish', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                content_ids: [contentId]
            })
        });
        
        const result = await response.json();
        
        if (result.status === 'completed') {
            alert('内容发布完成！');
            location.reload();
        } else {
            alert('发布失败：' + (result.message || '未知错误'));
        }
    } catch (error) {
        alert('发布失败：' + error.message);
    } finally {
        hideLoading();
    }
}

async function publishPendingContents() {
    if (!confirm('确定要发布所有待发布的内容吗？')) {
        return;
    }
    
    showLoading('正在批量发布内容，请稍候...');
    
    try {
        // 获取所有待发布的内容ID
        const pendingContents = document.querySelectorAll('.badge-warning');
        const contentIds = [];
        
        pendingContents.forEach(badge => {
            const item = badge.closest('.item');
            const publishBtn = item.querySelector('button[onclick*="publishContent"]');
            if (publishBtn) {
                const contentId = publishBtn.getAttribute('onclick').match(/\d+/)[0];
                contentIds.push(parseInt(contentId));
            }
        });
        
        if (contentIds.length === 0) {
            alert('没有待发布的内容');
            return;
        }
        
        const response = await fetch('/api/v1/publish/publish', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                content_ids: contentIds
            })
        });
        
        const result = await response.json();
        
        if (result.status === 'completed') {
            alert(`批量发布完成！处理了 ${contentIds.length} 个内容`);
            location.reload();
        } else {
            alert('批量发布失败：' + (result.message || '未知错误'));
        }
    } catch (error) {
        alert('批量发布失败：' + error.message);
    } finally {
        hideLoading();
    }
}

async function publishSelectedPlatform() {
    const platform = document.getElementById('platformFilter').value;
    if (!platform) {
        alert('请先选择要发布的平台');
        return;
    }
    
    if (!confirm(`确定要发布所有 ${platform} 平台的待发布内容吗？`)) {
        return;
    }
    
    showLoading(`正在发布 ${platform} 平台内容，请稍候...`);
    
    try {
        // 这里可以调用多平台发布API
        alert('功能开发中...');
    } catch (error) {
        alert('发布失败：' + error.message);
    } finally {
        hideLoading();
    }
}

function refreshContents() {
    location.reload();
}

function filterContents() {
    const platformFilter = document.getElementById('platformFilter').value;
    const statusFilter = document.getElementById('statusFilter').value;
    
    let url = '/admin/contents?';
    if (platformFilter) url += `platform=${platformFilter}&`;
    if (statusFilter) url += `status=${statusFilter}&`;
    
    window.location.href = url;
}

function showLoading(text) {
    document.getElementById('loadingText').textContent = text;
    document.getElementById('loadingModal').style.display = 'block';
}

function hideLoading() {
    document.getElementById('loadingModal').style.display = 'none';
}

function hideContentModal() {
    document.getElementById('contentModal').style.display = 'none';
}
</script>
{% endblock %}